//
//  ZMAlertView.swift
//  OnlineClassRoom
//
//  Created by 智蚂优服 on 2020/5/21.
//  Copyright © 2020 智蚂优服. All rights reserved.
//

import UIKit

class ZMAlertView: XMBaseView {
    // MARK: - alert 属性
    @IBOutlet weak var alertText: UILabel!
    @IBOutlet weak var alertTitle: UILabel!
    @IBOutlet weak var alertCancelBtn: UIButton!
    @IBOutlet weak var alertSureBtn: UIButton!
    @IBOutlet weak var closeBtn: UIButton!
    
    // MARK: - sheet属性
    /// 白色背景
    @IBOutlet weak var whiteView: UIView!
    /// 上部分取消，确定按钮
    @IBOutlet weak var topView: UIView!
    /// 列表
    @IBOutlet weak var sheetTable: UITableView!
    /// 列表高度
    @IBOutlet weak var sheetTableConstraint: NSLayoutConstraint!
    /// 底部取消按钮
    @IBOutlet weak var bottomCancelBtn: UIButton!
    
    /// 回调，selctIndex, -1 取消
    var zmAlertBlock:((_ selctIndex: Int)->())?
    private var sheetConfig = AlertConfig()
    
    public class func show(title:String = "提示",
                           content:String,
                           left:String?,
                           right:String,
                           onLeft:(()->())?,
                           onRight:(()->())?) {
        let config = AlertConfig()
        config.titleStr = content
        config.textStr = title
        config.sureBtnText = right
        if let left = left {
            config.cancelBtnText = left
        }
        else {
            config.hiddenCancel = true
        }

        ZMAlertView.alert(config: config) { (index) in
            if index >= 0 {
                if let onRight = onRight {
                    onRight()
                }
            } else {
                if let onLeft = onLeft {
                    onLeft()
                }
            }
        }
    }
    
    @discardableResult
    public class func alert(config: AlertConfig, clickBlock: ((_ selctIndex: Int)->())?) -> ZMAlertView {
        let v = ZMUtil.loadNibView(nibName: ZMAlertView.self)
        v.frame = config.from
        v.backgroundColor = config.backgroundColor
        v.zmAlertBlock = clickBlock
        v.alertText.text = config.textStr
        if let atr = config.attributedTitleStr {
            v.alertTitle.attributedText = atr
        } else {
            v.alertTitle.text = config.titleStr
        }
        v.alertCancelBtn.isHidden = config.hiddenCancel
        v.closeBtn.isHidden = config.hiddenClose
        v.alertCancelBtn.setTitle(config.cancelBtnText, for: .normal)
        v.alertCancelBtn.setTitleColor(config.cancelBtnTextColor, for: .normal)
        v.alertCancelBtn.backgroundColor = config.cancelBtnBgColor
        v.alertSureBtn.setTitle(config.sureBtnText, for: .normal)
        v.alertSureBtn.setTitleColor(config.sureBtnTextColor, for: .normal)
        v.alertSureBtn.backgroundColor = config.sureBtnBgColor
        APPWindow?.addSubview(v)
        return v
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.close666TouchOutSideRemove = true
        let line = UIView()
        line.backgroundColor = "#E5E5E5".zm.hex()
        alertCancelBtn.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.bottom.right.top.equalToSuperview()
            make.width.equalTo(1)
        }
    }

    public class func sheet(config: AlertConfig, clickBlock: ((_ selctIndex: Int)->())?) -> ZMAlertView {
        let v = ZMUtil.loadNibView(nibName: ZMAlertView.self)
        v.frame = config.from
        v.zmAlertBlock = clickBlock
        v.bottomCancelBtn.setTitle(config.cancelBtnText, for: .normal)
        v.sheetConfig = config
        v.sheetTable.reloadData()
        let height = CGFloat(config.sheetDataArr.count) * config.sheetCellHeight
        v.sheetTableConstraint.constant = height > SCREEN_W * 0.7 ? height : SCREEN_W * 0.7
        return v
    }
    
    @IBAction func cancelBtnClick(_ sender: UIButton) {
        self.removeFromSuperview()
        guard let block = zmAlertBlock else{
            return
        }
        block(-1)
    }
    
    @IBAction func sureBtnClick(_ sender: UIButton) {
        self.removeFromSuperview()
        guard let block = zmAlertBlock else{
            return
        }
        block(1)
    }
}

extension ZMAlertView: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sheetConfig.sheetDataArr.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return CGFloat(sheetConfig.sheetCellHeight)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "zmAlertSheetCell", for: indexPath) as! zmAlertSheetCell
        let attrString = NSMutableAttributedString(string: sheetConfig.sheetDataArr[indexPath.row])
        let attr: [NSMutableAttributedString.Key: Any]?
        if sheetConfig.selectSheetDataArr.contains(sheetConfig.sheetDataArr[indexPath.row]) {
            attr = sheetConfig.selectSheetOptionAttributes
        } else {
            attr = sheetConfig.sheetOptionAttributes
        }
        attrString.addAttributes(attr!, range: NSRange(location: 0, length: attrString.length))
        cell.sheetOption.attributedText = attrString
        cell.sheetOption.text = sheetConfig.sheetDataArr[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.removeFromSuperview()
        guard let block = zmAlertBlock else {
            return
        }
        block(indexPath.row)
    }
}

class zmAlertSheetCell: UITableViewCell {
    lazy var sheetOption: UILabel = {
        let lab = UILabel()
        self.contentView.addSubview(lab)
        lab.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview()
            make.left.equalTo(16)
            make.right.equalTo(-60)
        }
        return lab
    }()
    
    lazy var optionSelectBtn: UIButton = {
        let btn = UIButton()
        self.contentView.addSubview(btn)
        return btn
    }()
}

// MARK: - 属性配置
class AlertConfig {
    convenience init(_ textStr: String = "提示", _ titleStr: String = "") {
        self.init()
        self.textStr = textStr
        self.titleStr = titleStr
    }
    
    public var from = SCREEN_BOUNDS
    /// 背景色
    public var backgroundColor = UIColor.zm.color(hexString: "#000000", 0.65)
    /// 标题
    public var textStr: String = "提示"
    /// 内容
    public var titleStr: String = "提示内容"
    /// 内容属性字体
    public var attributedTitleStr : NSAttributedString?
    /// 取消按钮背景，默认#CCCCCC
    public var cancelBtnBgColor: UIColor = .white
    /// 取消按钮文字颜色，默认白色
    public var cancelBtnTextColor: UIColor = "#000000".zm.hex()
    /// 取消按钮文字,默认取消
    public var cancelBtnText: String = "取消"
    /// 确定按钮背景，默认主题色
    public var sureBtnBgColor: UIColor = "#DE3F26".zm.hex()
    /// 确定按钮，默认主题色
    public var sureBtnTextColor: UIColor = .white
    /// 确定按钮文字，默认确定
    public var sureBtnText: String = "确定"
    /// 隐藏取消按钮
    public var hiddenCancel: Bool = false
    /// 隐藏叉叉按钮
    public var hiddenClose: Bool = true
    /// sheet 数据
    public var sheetDataArr = [String]()
    /// sheet 已选择数据，回显
    public var selectSheetDataArr = [String]()
    /// sheet cell高度
    public var sheetCellHeight: CGFloat = 44.0
    /// sheet 默认字体属性
    public var sheetOptionAttributes = [NSAttributedString.Key.font: UIFont.zm.fontRegular(), NSAttributedString.Key.foregroundColor: UIColor.zm.color999999()]
    /// sheet 已选择字体属性
    public var selectSheetOptionAttributes = [NSAttributedString.Key.font: UIFont.zm.fontRegular(), NSAttributedString.Key.foregroundColor: UIColor.zm.color333333()]
    
}
